package com.zzyy.study.myconsumer;

import cn.hutool.json.JSONUtil;
import com.zzyy.study.config.RabbitMQConfiguration;
import com.zzyy.study.entities.OrderMsg;
import com.zzyy.study.mq.consumer.AbstractSequentialMsgConsumer;
import com.zzyy.study.mq.dto.Msg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 单独一个消费者类OrderConsumerByInOrder，等价于模拟消费者微服务springboot启动，懒得新建
 * 一个消费者微服务了，OrderConsumerByInOrder类代替消费者
 * @auther zzyy
 * @create 2024-08-28 23:05
 */
@Slf4j
@Component
public class OrderConsumerByInOrder extends AbstractSequentialMsgConsumer<OrderMsg, Msg<OrderMsg>>
{
    //消费方启动了5个消费者，模拟5个消费者同时去拿消息，测试效果是否可以确保消息消费的顺序性
    @Override
    @RabbitListener(queues = RabbitMQConfiguration.Order.QUEUE, concurrency = "5")
    public void dispose(Message message) {

        //dispose_WithOut_InOrder(message);

        dispose_InOrder(message);
    }

    private void dispose_InOrder(Message message)
    {
        super.dispose(message);
    }

    private void dispose_WithOut_InOrder(Message message)
    {
        Msg<OrderMsg> msg = getMsg(message);
        String log = "===》没有确保顺序消费的情况,消息编号：" + msg.getSequentialMsgNumbering() + ",消息体：" + JSONUtil.toJsonStr(msg.getBody());
        System.err.println(log);
    }

    @Override
    protected void sequentialMsgConsume(Msg<OrderMsg> msg) {
        String log = "===》顺序消息消费,消息编号：" + msg.getSequentialMsgNumbering() + ",消息体：" + JSONUtil.toJsonStr(msg.getBody());
        System.err.println(log);
        //这里休眠500ms，模拟耗时的业务操作
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
